package com.cg.leetcode;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 515.在每个树行中找最大值
 *
 * @program: LeetCode->LeetCode_515
 * @author: cg
 * @create: 2022-04-19 20:44
 **/
public class LeetCode_515 {

    @Test
    public void test515() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(3);
        root.left.left = new TreeNode(5);
        root.left.right = new TreeNode(3);

        root.right = new TreeNode(2);
        root.right.right = new TreeNode(9);
        System.out.println(largestValues(root));
    }

    /**
     * 给定一棵二叉树的根节点 root ，请找出该二叉树中每一层的最大值。
     * <p>
     * 示例1：
     * 输入: root = [1,3,2,5,3,null,9]
     * 输出: [1,3,9]
     * <p>
     * 示例2：
     * 输入: root = [1,2,3]
     * 输出: [1,3]
     * <p>
     * 提示：
     * 二叉树的节点个数的范围是 [0,10^4]
     * -2^31 <= Node.val <= 2^31 - 1
     *
     * @param root
     * @return
     */
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return res;
        }
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                max = Math.max(max, node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            res.add(max);
        }
        return res;
    }

}
